package com.atguigu.spzx.cloud.order.service.impl;

import com.atguigu.spzx.cloud.order.entity.Order;
import com.atguigu.spzx.cloud.order.entity.User;
import com.atguigu.spzx.cloud.order.feign.UserFeignClient;
import com.atguigu.spzx.cloud.order.mapper.OrderMapper;
import com.atguigu.spzx.cloud.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

//    @Autowired
//    private RestTemplate restTemplate;
//
//    @Autowired
//    private DiscoveryClient discoveryClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Order findOrderByOrderId(Long orderId) {
//        return orderMapper.findOrderByOrderId(orderId);

        Order order = orderMapper.findOrderByOrderId(orderId);
        //远程调用
        User user = userFeignClient.findUserByUserId(order.getUserId());
        order.setUser(user);
        return order;

        /*//根据id查询订单数据
        Order order = orderMapper.findOrderByOrderId(orderId);
        //根据服务器名称从注册中心获取服务器实例列表
        ServiceInstance serviceInstance = chooseServiceInstance("spzx-cloud-user");
        //发起远程调用
        User user = restTemplate.getForObject("http//" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/api/user/findUserByUserId/" + order.getUserId(), User.class);
        order.setUser(user);
        return order;
    }

    public ServiceInstance chooseServiceInstance(String applicationName) {
        //获取服务实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances(applicationName);
        //编写一个简易的随机负载均衡算法
        int size = instances.size();
        Random random = new Random();
        int instanceIndex = random.nextInt(size);
        ServiceInstance serviceInstance = instances.get(instanceIndex);
        return serviceInstance;*/
    }

}